import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from celery_tasks.email.tasks import send_active_email

from .models import User, Address


class CreateUserSerializer(serializers.ModelSerializer):
    # TODO 创建用户的序列化器3

    password2 = serializers.CharField(label='确认密码' ,write_only=True)
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    allow = serializers.CharField(label='阅读协议',write_only=True)
    token = serializers.CharField(label='JWT token',read_only=True)

    class Meta:
        model = User
        fields = ('id','username','password','password2','sms_code','mobile','allow','token')
        extra_kwargs = {
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length':'仅允许8-20个字符的密码',
                    'max_length':'仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self,value):
        # 验证手机号
        if not re.match(r'^1[3-9]\d{9}$',value):
            raise serializers.ValidationError('手机号码格式错误')
        return value


    def validate_allow(self,value):
        # 检查用户是否同意用户协议
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value


    def validate(self,data):
        # 判断两次密码是否正确
        if data['password'] != data['password2']:
            raise serializers.ValidationError('两次密码不一致')

        # 判断手机验证码是否正确

        # 先连接redis数据库
        redis_conn = get_redis_connection('verify_codes')

        # 获取参数中的值
        mobile = data['mobile']
        print(data)
        print("手机号%s" % mobile)
        # 取出redis数据库中的值
        real_redis_code = redis_conn.get("sms_%s" % mobile)
        print(11111111)
        print('取到的%s' % real_redis_code)

        if real_redis_code is None:
            raise serializers.ValidationError('错误验证码')

        if data['sms_code'] != real_redis_code.decode():
            raise  serializers.ValidationError('短信验证码错误')

        return data

# TODO 重写保存数据的方法 增强加密效果
    def create(self,validated_data):

        # 先移除数据库中模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # user = User.objects.create(**validated_data)


        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()

        # 签发 jwt token

        jwt_payload_hander = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_hander(user)
        token = jwt_encode_handler(payload)

        # 给user 模型添加token属性
        user.token = token
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    """用户详细信息的序列化器"""

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """验证邮箱序列化器"""

    class Meta:
        model = User
        fields = ('id','email')


    def update(self, instance, validated_data):
        # instance 传过来的就是传过来的 user对象
        email = validated_data['email'] #从视图中取出 用户输入的邮箱地址
        # 将邮箱地址保存致 用户对象中
        instance.email = email
        instance.save()

        # 生成激活地址
        url = instance.genrate_verify_email_url()

        # 发送邮件
        send_active_email.delay(email,url)
        return instance


    #  TODO 用户地址序列化器
class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


# 收货地址的序列化器
class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """

    class Meta:
        model = Address
        fields = ('title',)














